//
//  M_CartCell.swift
//  letuofu
//
//  Created by WH-JS on 2019/12/17.
//  Copyright © 2019 WH-JS. All rights reserved.
//

import UIKit

class M_CartCell: UITableViewCell,UITextFieldDelegate {
    //定义一个闭包类型
    typealias editNumBlock = (_ num: Int) -> Void
    //声明一个变量
    var editNumBack: editNumBlock?
    //定义一个方法,方法的参数为和swiftBlock类型一致的闭包,并赋值给callBack
    func callEditBlock(block: @escaping editNumBlock) {
        editNumBack = block
    }
    
    
    //定义一个闭包类型
    typealias selNumBlock = () -> Void
    //声明一个变量
    var selNumBack: selNumBlock?
    //定义一个方法,方法的参数为和swiftBlock类型一致的闭包,并赋值给callBack
    func callselBlock(block: @escaping selNumBlock) {
        selNumBack = block
    }
    
    //定义一个闭包类型
    typealias detailBlock = () -> Void
    //声明一个变量
    var detailBack: detailBlock?
    //定义一个方法,方法的参数为和swiftBlock类型一致的闭包,并赋值给callBack
    func calldetailBlock(block: @escaping detailBlock) {
        detailBack = block
    }
    
    let selImg = Button()
    let productImg = UIImageView()
    let priceImg = UIImageView()
    let addBtn = Button()
    let cutBtn = Button()
    let detailBtn = Button()
    let titleLab = UILabel()
    let priceLab = UILabel()
    let NumLab = TextField()
    let jdLab = UILabel()
    let shixiaoLab = UILabel()
    var celldata : [String : Any?]? {
        didSet{
            loadData()
        }
    }
    
    let noneBgview = UIView()
    var nonePro = false {
        didSet{
            if nonePro {
                noneBgview.isHidden = false
                shixiaoLab.isHidden = false
                addBtn.isHidden = true
                cutBtn.isHidden = true
                selImg.isHidden = true
                NumLab.isHidden = true
            }
            else {
                noneBgview.isHidden = true
                shixiaoLab.isHidden = true
                addBtn.isHidden = false
                cutBtn.isHidden = false
                selImg.isHidden = false
                NumLab.isHidden = false
            }
        }
        
    }
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        self.selectionStyle = .none
        setupUI()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }
    
    func setupUI() {
        self.backgroundColor = .white
        
        drawButton(button: selImg,imageNamed: "weixuanzhong_30") { (make) in
            make.centerY.equalToSuperview()
            make.left.equalToSuperview().offset(10)
        }
        selImg.setImage(UIImage.init(named: "xuanzhong_31"), for: .selected)
        selImg.setImage(UIImage.init(named: "weixuanzhong_30"), for: .normal)
        selImg.addTarget(self, action: #selector(_selButtonClick(button:)), for: .touchUpInside)
        selImg.hitEdgInsets = .init(top: -30, left: -10, bottom: -30, right: -10)
        
        drawLabel(label: shixiaoLab, text: "失效", fontSize: 9, textColor: .white) { (make) in
            make.center.equalTo(selImg)
            make.width.equalTo(25)
            make.height.equalTo(15)
        }
        shixiaoLab.textAlignment = .center
        shixiaoLab.backgroundColor = .x999999
        shixiaoLab.layer.cornerRadius = 7.5
        shixiaoLab.clipsToBounds = true
        
        drawImage(imageView: productImg, named: nil) { (make) in
            make.left.equalToSuperview().offset(39)
            make.centerY.equalToSuperview()
            make.width.equalTo(50)
            make.height.equalTo(50)
        }
        productImg.cornerRadius(4.0).clipsToBounds = true
        productImg.layer.borderWidth = 0.5
        productImg.layer.borderColor = UIColor.xEEEEEE.cgColor
        
        productImg.drawLabel(label: jdLab,text: "京东配送", fontSize: 9, textColor: .white) { (make) in
            make.top.equalToSuperview()
            make.right.equalToSuperview()
            make.height.equalTo(12)
            make.width.equalTo(40)
        }
        jdLab.font = .boldSystemFont(ofSize: 9)
        jdLab.backgroundColor = .xFC4C02
        jdLab.textAlignment = .center
        
        drawLabel(label: titleLab, text: "", fontSize: 14, fontWeight: .regular, textColor: .x333333) { (make) in
            make.left.equalTo(productImg.snp.right).offset(10)
            make.top.equalTo(productImg.snp.top)
            make.width.equalTo(190)
        }
        titleLab.numberOfLines = 2
        
        drawImage(imageView: priceImg, named: "jifen_13") { (make) in
            make.left.equalTo(productImg.snp.right).offset(10)
            make.bottom.equalTo(productImg.snp.bottom)
        }
        drawLabel(label: priceLab, text: "", fontSize: 15, fontWeight: .regular, textColor: .xFC4C02) { (make) in
            make.left.equalTo(priceImg.snp.right).offset(8)
            make.bottom.equalTo(productImg.snp.bottom).offset(3)
        }
        
        drawButton(button: addBtn, imageNamed: "jia_27") { (make) in
            make.right.equalToSuperview().offset(-10)
            make.bottom.equalTo(-23)
        }
        addBtn.hitEdgInsets = .init(top: -20, left: 0, bottom: -20, right: -20)
        addBtn.setImage(UIImage.init(named: "jia_28"), for: .selected)
        addBtn.addTarget(self, action: #selector(_addButtonClick(button:)), for: .touchUpInside)
        
        drawTextField(textField: NumLab, placeholder: "", fontSize: 12, keyboardType: .numberPad, returnKeyType: .done) { (make) in
            make.right.equalTo(addBtn.snp.left).offset(-10)
            make.bottom.equalTo(-19)
            make.width.equalTo(35)
            make.height.equalTo(15)
        }
        NumLab.delegate = self
        NumLab.textAlignment = .center
        NumLab.backgroundColor = .xF2F2F2
        NumLab.layer.cornerRadius = 7.5
        
        drawButton(button: cutBtn, imageNamed: "jian_29") { (make) in
            make.right.equalTo(NumLab.snp.left).offset(-10)
            make.centerY.equalTo(addBtn)
        }
        cutBtn.hitEdgInsets = .init(top: -20, left: -20, bottom: -20, right: 0)
        cutBtn.setImage(UIImage.init(named: "jian_28"), for: .selected)
        cutBtn.addTarget(self, action: #selector(_cutButtonClick(button:)), for: .touchUpInside)
        
        drawButton(button: detailBtn,title: "", titleColor: .clear, fontSize: 1) { (make) in
//            make.top.bottom.equalToSuperview()
            make.height.equalTo(80)
            make.width.equalTo(260)
            make.centerX.equalToSuperview().offset(-20)
            make.centerY.equalToSuperview()
        }
        detailBtn.addTarget(self, action: #selector(_detailButtonClick(button:)), for: .touchUpInside)
        
        //画横线
        let line = drawView { (make) in
            make.left.equalToSuperview().offset(108.5)
            make.right.equalToSuperview().offset(-10)
            make.bottom.equalToSuperview()
            make.height.equalTo(1)
        }
        line.backgroundColor = .xF2F2F2
        
        drawView(view: noneBgview) { (make) in
            make.left.equalTo(productImg.snp.right)
            make.right.equalToSuperview()
            make.centerY.equalToSuperview()
            make.height.equalToSuperview()
        }
        noneBgview.backgroundColor = .init(white: 1, alpha: 0.5)
        noneBgview.isHidden = true
    }
    
    func loadData() {
        if var urlstring = celldata?.getString("listPicURL") {
            if celldata?.getString("zoneCode") == "105002" {
                urlstring = (JDIMG_HOST_URL+urlstring).addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!
                jdLab.isHidden = false
            }
            else {
                urlstring = (IMG_HOST_URL+urlstring).addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!
                jdLab.isHidden = true
            }
            let url = URL(string: urlstring)
            productImg.sd_setImage(with: url) { (img, error, type, u) in
                if error != nil {
                    self.productImg.image = img
                }
            }
        }else{
            productImg.image = nil
        }
        titleLab.text = celldata?.getString("productName")
        priceLab.text = anyToString(celldata?["productPrice"]!)
        NumLab.text = anyToString(celldata?.getInt("productNum"))
        if let num = anyToInt(NumLab.text) {
            if num == 1 {
                cutBtn.isSelected = true
            }
            else {
                cutBtn.isSelected = false
            }
            
            if num == 999 {
                addBtn.isSelected = true
            }
            else {
                addBtn.isSelected = false
            }
        }
        let sel = celldata?.getBool("isSelected") ?? false
        selImg.isSelected = sel
    }
    
    @objc func _selButtonClick(button: Button) {
        // Configure the view for the selected state
        button.isSelected = !button.isSelected

        if selNumBack != nil {
            selNumBack!()
        }
    }
    
    
    @objc func _addButtonClick(button: Button) {
        if var num = anyToInt(NumLab.text) {
            if num >= 999 {
                let popup = PopupBox(infoText: "商品已超过最大购买数量",onTop: true)
                if let vc = UIViewController.topMostController() {
                    popup.show(vc: vc)
                }
                return
            }
            num += 1
//            NumLab.text = anyToString(num)
            if editNumBack != nil {
                editNumBack!(num)
            }
        }
    }
    
    @objc func _detailButtonClick(button: Button) {
        if detailBack != nil {
            detailBack!()
        }
    }
    
    @objc func _cutButtonClick(button: Button) {
        if var num = anyToInt(NumLab.text) {
            if num <= 1 {
                let popup = PopupBox(infoText: "商品数量必须大于0")
                if let vc = UIViewController.topMostController() {
                    popup.show(vc: vc)
                }
                return
            }
            num -= 1
//            NumLab.text = anyToString(num)
            if editNumBack != nil {
                editNumBack!(num)
            }
        }
    }
    
    //UITextFieldDelegate
    func textFieldShouldEndEditing(_ textField: UITextField) -> Bool {
        
        if let num = anyToInt(NumLab.text) {
            if num < 1 {
                let popup = PopupBox(infoText: "商品数量必须大于0",onTop: true)
                if let vc = UIViewController.topMostController() {
                    popup.show(vc: vc)
                }
                return false
            }
            else if num > 999 {
                let popup = PopupBox(infoText: "商品已超过最大购买数量",onTop: true)
                if let vc = UIViewController.topMostController() {
                    popup.show(vc: vc)
                }
                return false
            }
            return true
        }
        else {
            return false
        }
        
        
    }
    func textFieldDidEndEditing(_ textField: UITextField) {
        if let num = anyToInt(NumLab.text) {
            if editNumBack != nil {
                editNumBack!(num)
            }
        }
    }
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
//        print(textField.text ?? "")
//        print(string)
        if textField.text?.count ?? 0 > 2 && string != "" {
            return false
        }
        return true
    }
}

class M_CartSectionHeadView: UIView {
    var zoneCode : ZoneCodeModel
    let selBtn = Button()
    
    init(zone: ZoneCodeModel) {
        self.zoneCode = zone
        super.init(frame: .zero)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func draw(_ rect: CGRect) {
        drawButton(button: selBtn,imageNamed: "weixuanzhong_30") { (make) in
            make.centerY.equalToSuperview()
            make.left.equalToSuperview().offset(10)
        }
        selBtn.hitEdgInsets = .init(top: -20, left: -20, bottom: -20, right: -20)
        selBtn.addTarget(self, action: #selector(_selButtonClick(button:)), for: .touchUpInside)
        
        drawImage(named: "zhiyingdianpu_33") { (make) in
            make.centerY.equalToSuperview()
            make.left.equalToSuperview().offset(38.5)
        }
        
        drawLabel(text: zoneCode.name, fontSize: 15, textColor: .x333333) { (make) in
            make.left.equalToSuperview().offset(64.5)
            make.centerY.equalToSuperview()
        }
        
        drawImage(named: "youjiantou_55") { (make) in
            make.centerY.equalToSuperview()
            make.left.equalToSuperview().offset(128.5)
        }
    }
    
    @objc func _selButtonClick(button: Button) {
    }
}
